<template>
  <div>
    <ZgDialog
      :width="view.width"
      :top="view.top"
      :title="view.title"
      v-model="visible"
      @ok="save">
      <div v-if="initLoading">
        正在初始化配置数据...
      </div>
      <div v-else>
        <div v-if="!hasInit">
          初始化配置数据失败
        </div>
        <div :style="{padding:`${layout.视图边距}px`}">
          <a-row :gutter="layout.左右间距">
            <a-col :offset="c.offset" :span="c.span" v-for="(c,i) in columns" :key="`column${i}`">
              <div :class="layout.标签对齐==='top'?'':'flx-s'" :style="{marginBottom:`${layout.上下间距}px`}">
                <div :class="layout.标签对齐==='right'?'tar':'tal'" class="mr10 flx-s" :style="{width:`${layout.标签宽度}px`}">
                  <ZgCheckbox class="mr10" v-model="obj[`${c.code}_ck`]"></ZgCheckbox>
                  {{ c.name }}
                </div>
                <div class="flx-1" :class="layout.标签对齐==='top'?'mt10':''">
                  <ZgInput v-model="obj[c.code]" v-if="c.type==='单行文本'"></ZgInput>
                  <ZgNumber v-model="obj[c.code]" v-if="c.type==='整数'"></ZgNumber>
                  <ZgNumber v-model="obj[c.code]" v-if="c.type==='浮点数'" isFloat></ZgNumber>
                  <ZgCheckbox v-model="obj[c.code]" v-if="c.type==='单选框'"></ZgCheckbox>
                  <ZgSelectMany v-model="obj[c.code+'_multi']" v-if="c.type==='多选'" :code="c.extra.字典类型"></ZgSelectMany>
                  <ZgDatePicker v-model="obj[c.code]" v-if="c.type==='日期'"></ZgDatePicker>
                  <ZgDateTimePicker v-model="obj[c.code]" v-if="c.type==='日期时间'"></ZgDateTimePicker>
                  <ZgDictionary v-model="obj[c.code]" v-if="c.type==='字典'" :code="c.extra.字典类型"></ZgDictionary>
                  <ZgSwitch v-model="obj[c.code]" v-if="c.type==='开关'"></ZgSwitch>
                  <ZgTextarea v-model="obj[c.code]" v-if="c.type==='多行文本'" :rows="parseInt(c.extra.行数)"></ZgTextarea>
                  <ZgTinymce v-model="obj[c.code]" v-if="c.type==='富文本'" :height="parseInt(c.extra.高度)"></ZgTinymce>
                  <ZgUpImg v-model="obj[c.code]" v-if="c.type==='图片'"></ZgUpImg>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
    </ZgDialog>
  </div>
</template>
<script>
import dayjs from 'dayjs'
export default {
  props: {
    view: {
      type: Object,
      default: () => {
        return {
          width: '60%',
          top: '5%',
          title: '批量修改数据'
        }
      }
    },
    table: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      ids: [],
      visible: false,
      hasInit: false,
      initLoading: false,
      layout: {},
      columns: [],
      initFormulas: [],
      changeFormulas: [],
      submitFormulas: [],
      validUrl: '',
      // 是否验证正则
      isRegexEnabled: true,
      // 是否调用远程验证接口
      isRemoteCheckEnabled: true,
      // 是否执行初始化公式
      isInitFormulaEnabled: true,
      // 是否执行数据变化公式
      isChangeFormulaEnabled: true,
      // 是否执行提交前公式
      isSubmitFormulaEnabled: true,
      obj: null
    }
  },
  watch: {
    table () {
      this.init()
    },
    obj: {
      handler (newVal, oldVal) {
        if (this.hasInit) {
          // 数据变化时执行公式
          this.isChangeFormulaEnabled && this.doFormula(this.changeFormulas)
        }
      },
      deep: true
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    open (ids) {
      this.ids = ids
      this.visible = true
    },
    doFormula (formulas) {
      if (!formulas || formulas.length === 0) { return }
      const arr = []
      formulas.forEach(t => {
        try {
          // eslint-disable-next-line no-eval
          eval(t)
        } catch (e) {
          arr.push(t)
        }
      })
      if (arr.length > 0) {
        console.log(`有${arr.length}个公式执行错误`)
      }
    },
    init () {
      this.hasInit = false
      this.initLoading = true
      // 获取布局
      this.layout = JSON.parse(this.table.batchLayout)
      // 获取字段
      this.columns = this.table.batchColumns.map(t => {
        t.sort = t.sort || 0
        t.span = t.span || 24
        t.offset = t.offset || 0
        return t
      })
      this.$nextTick(() => {
        this.columns.sort((a, b) => {
          return a.sort - b.sort
        })
      })
      // 获取公式
      const formulas = this.table.formulas.filter(f => {
        return f.cata === '批量更新'
      })
      this.initFormulas = formulas.filter(f => {
        return f.triggerMode === '初始化时'
      }).map(f => {
        return f.content
      })
      this.changeFormulas = formulas.filter(f => {
        return f.triggerMode === '数据变化时'
      }).map(f => {
        return f.content
      })
      this.submitFormulas = formulas.filter(f => {
        return f.triggerMode === '提交时'
      }).map(f => {
        return f.content
      })
      // 获取远程校验接口地址
      this.validUrl = this.table.validUrl
      // 生产数据对象
      const json = {}
      this.columns.forEach(c => {
        if (['整数', '浮点数'].includes(c.type)) {
          json[c.code] = Number(c.defaultVal) || 0
        } else if (['日期'].includes(c.type)) {
          json[c.code] = c.defaultVal || dayjs().format('YYYY-MM-DD')
        } else if (['日期时间'].includes(c.type)) {
          json[c.code] = c.defaultVal || dayjs().format('YYYY-MM-DD HH:mm:ss')
        } else if (['单选框', '开关'].includes(c.type)) {
          json[c.code] = c.defaultVal === '1'
        } else if (['多选'].includes(c.type)) {
          json[c.code + '_multi'] = c.defaultVal.split(',') || []
          json[c.code] = c.defaultVal || ''
        } else {
          json[c.code] = c.defaultVal || ''
        }
        json[`${c.code}_ck`] = false
      })
      this.obj = json
      // 初始化时执行公式
      this.isInitFormulaEnabled && this.doFormula(this.initFormulas)
      // 初始化配置完成
      setTimeout(() => {
        this.initLoading = false
        this.hasInit = true
      }, 1000)
    },
    save () {
      // 验证是否选择了设置的数据
      const hasCheckedProperty = this.columns.some(c => {
        return this.obj[`${c.code}_ck`] === true
      })
      if (!hasCheckedProperty) {
        this.$warn('请选择要设置的属性')
        return
      }

      // 选择的属性必须要设置值
      const checkedPropArray = this.columns.filter(c => {
        return this.obj[`${c.code}_ck`] === true
      })
      for (const i in checkedPropArray) {
        const column = checkedPropArray[i]
        const value = this.obj[column.code]
        if (['多选'].includes(column.type)) {
          this.obj[column.code] = this.obj[column.code + '_multi'].join(',')
          continue
        }
        if (['单选框', '开关'].includes(column.type)) {
          continue
        }
        if (!value || value.length === 0) {
          this.$error({ title: `请设置${column.name}` })
          return
        }
      }

      // 选择的属性验证正则，只验证单行文本
      if (this.isRegexEnabled) {
        const inputColumns = checkedPropArray.filter(c => {
          return c.type === '单行文本' && c.regex && c.regex.length > 0
        })
        for (const i in inputColumns) {
          const column = inputColumns[i]
          const value = this.obj[column.code]
          const reg = new RegExp(column.regex)
          if (!reg.test(value)) {
            this.$error(column.errorMsg)
            return
          }
        }
      }
      // 提交前执行公式
      this.isSubmitFormulaEnabled && this.doFormula(this.submitFormulas)
      // 远程接口验证
      if (this.isRemoteCheckEnabled && this.validUrl && this.validUrl.length > 0) {
        this.$http.post(this.validUrl, Object.assign({ ids: this.ids }, this.obj), () => {
          this.$http.post('/zg-autoform/table/data/batch/' + this.table.code, Object.assign({ ids: this.ids }, this.obj), () => {
            this.visible = false
            this.$emit('ok')
          })
        })
      } else {
        this.$http.post('/zg-autoform/table/data/batch/' + this.table.code, Object.assign({ ids: this.ids }, this.obj), () => {
          this.visible = false
          this.$emit('ok')
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
